package us.versus.them.libounce;

import flash.display.Graphics;

class Line {

	public static var NO_TIME = 1000.0;

	public var x0:Float;
	public var y0:Float;
	public var x1:Float;
	public var y1:Float;

	public var xdiff:Float;
	public var ydiff:Float;

	var normal_x:Float;
	var normal_y:Float;

	public function new( ?x0:Float , ?y0:Float , ?x1:Float , ?y1:Float ) {
		if ( null == x0 ) x0 = 0;
		if ( null == y0 ) y0 = 0;
		if ( null == x1 ) x1 = 0;
		if ( null == y1 ) y1 = 0;
		this.set( x0 , y0 , x1 , y1 );
	}

	public function ball( ball:Ball ) {
		this.set( 
			ball.x
			, ball.y
			, ball.x + ball.dx
			, ball.y + ball.dy
		);
	}

	public function set( x0:Float , y0:Float , x1:Float , y1:Float ) {
		this.x0 = x0;
		this.y0 = y0;
		this.x1 = x1;
		this.y1 = y1;
		xdiff = x1 - x0;
		ydiff = y1 - y0;

		normal_x = ydiff;
		normal_y = -xdiff;

		var l2 = ( normal_x * normal_x + normal_y * normal_y );
		
		if ( 0 != l2 ) {
			l2 = Math.sqrt( l2 );
			normal_x /= l2;
			normal_y /= l2;
		}
	}

	public function intersectionTime( that:Line ) {
		var denominator = (
			-normal_x * that.xdiff
			-normal_y * that.ydiff
		);
	    var t = NO_TIME;
		if ( 0 != denominator ) {
			var numerator = ( 0
				+ normal_x * ( that.x0 - this.x0 )
				+ normal_y * ( that.y0 - this.y0 )
			);
			t = numerator / denominator;
		}
		return t;
	}

	public function fullInteresction( that:Line ) {
		var t = intersectionTime( that );
		if ( t < 0 || t > 1 ) {
			t = NO_TIME;
		} else {
			var s = that.intersectionTime( this );
			if ( s < 0 || s > 1 ) {
				t = NO_TIME;
			}
		}
		return t;
	}

	public function wrap( width:Float, height:Float ) {
		this.x0 = wrapAround( this.x0, width );
		this.y0 = wrapAround( this.y0, height );
		this.x1 = wrapAround( this.x1, width );
		this.y1 = wrapAround( this.y1, height );
	}

	public static inline function wrapAround( v:Float, max:Float ) {
		while ( v < 0 ) v += max;
		while ( v > max ) v -= max;
		return v;
	}

	public function draw( graphics:Graphics ) {
		graphics.lineStyle( 2, 0x0000AB );
		graphics.moveTo( x0, y0 );
		graphics.lineTo( x1, y1 );
	}

	public function length() {
		return Math.sqrt( xdiff * xdiff + ydiff * ydiff );
	}

}
